import React, { useState, useEffect } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Table,
  Image,
  Switch,
  Space,
  Modal,
  Upload
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { NavLink } from 'react-router-dom'
import { swiperQuery, swiperItem } from '@/types/swiper'
import { getSwiperList } from '@/api/swiper'
import type { ColumnsType } from 'antd/es/table'
import type { RcFile, UploadProps } from 'antd/es/upload'
import type { UploadFile } from 'antd/es/upload/interface'

export default function index () {
  const [swiperList, setSwiperList] = useState([] as swiperItem[])
  const [total, setTotal] = useState(0)
  //查询模型
  const [swipeQuery, setSwipeQuery] = useState<swiperQuery>({
    page: 1,
    pageSize: 2,
    link: '',
    alt: ''
  })
  const [link, setLink] = useState('')
  const [alt, setAlt] = useState('')
  const [swiperForm, setSwiperForm] = useState<swiperItem>({
    img: '',
    alt: '',
    link: '',
    bannerid: '',
    flag: true
  })

  //获取数据
  const getSwiperListData = async () => {
    const res = await getSwiperList(swipeQuery)

    setSwiperList(res.data.items)
    setTotal(res.data.total)
  }
  useEffect(() => {
    getSwiperListData()
  }, [swipeQuery])
  //

  const columns: ColumnsType<swiperItem> = [
    {
      title: '轮播图图片',
      dataIndex: 'img',
      render: img => <Image width={60} height={60} src={img} />
    },
    {
      title: '跳转地址',
      dataIndex: 'link',
      render: link => (
        <a href={link} target='_blank'>
          {link}
        </a>
      )
    },
    {
      title: '轮播图alt',
      dataIndex: 'alt'
    },
    {
      title: '启用/禁用',
      dataIndex: 'flag',
      render: flag => {
        return <Switch checked={flag} />
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_, recod) => {
        return (
          <Space>
            <Button type='primary' onClick={() => {}}>
              修改
            </Button>
            <Button type='primary' danger onClick={() => {}}>
              删除
            </Button>
          </Space>
        )
      }
    }
  ]
  //新增&修改
  const [open, setOpen] = useState(false)
  const [mode, setMode] = useState<'add' | 'edit'>('add')
  const [formInstance] = Form.useForm()

  const submit = () => {}
  //图片上传
  const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result as string)
      reader.onerror = error => reject(error)
    })

  const [previewOpen, setPreviewOpen] = useState(false)
  const [previewImage, setPreviewImage] = useState('')
  const [previewTitle, setPreviewTitle] = useState('')
  const [fileList, setFileList] = useState<UploadFile[]>([
    {
      uid: swiperForm.bannerid,
      name: swiperForm.alt,
      url: swiperForm.img
    }
  ])

  const handleCancel = () => setPreviewOpen(false)

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile)
    }

    setPreviewImage(file.url || (file.preview as string))
    setPreviewOpen(true)
    setPreviewTitle(
      file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1)
    )
  }

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>
    setFileList(newFileList)

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  )

  return (
    <div>
      <Card>
        <Breadcrumb
          items={[
            {
              title: <NavLink to='/'>首页</NavLink>
            },
            {
              title: '轮播图管理'
            },
            {
              title: '轮播图列表'
            }
          ]}
        />
        <Form layout='inline' style={{ marginTop: 20 }} size='large'>
          <Form.Item label='跳转链接'>
            <Input
              placeholder='请输入跳转链接'
              value={link}
              onChange={e => setLink(e.target.value)}
            />
          </Form.Item>
          <Form.Item label='图片alt'>
            <Input
              placeholder='请输入图片alt'
              value={alt}
              onChange={e => setAlt(e.target.value)}
            />
          </Form.Item>
          <Form.Item>
            <Button
              type='default'
              onClick={() => {
                setLink('')
                setAlt('')
                setSwipeQuery({ ...swipeQuery, link, alt, page: 1 })
              }}
            >
              清空
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type='primary'
              onClick={() => {
                setSwipeQuery({ ...swipeQuery, link, alt })
              }}
            >
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button type='default' onClick={() => setOpen(true)}>
              新增轮播图
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card style={{ marginTop: 10 }}>
        <Table
          size='large'
          columns={columns}
          rowKey='bannerid'
          dataSource={swiperList}
          pagination={{
            position: ['bottomCenter'],
            current: swipeQuery.page,
            pageSize: swipeQuery.pageSize,
            pageSizeOptions: [1, 2, 5, 10],
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共${total}条`,
            onChange: (page, pageSize) => {
              setSwipeQuery({ ...swipeQuery, page, pageSize })
            }
          }}
        />
      </Card>
      <Modal
        style={{ width: 800 }}
        title={mode == 'add' ? '新增用户' : '修改用户'}
        open={open}
        onOk={submit}
        onCancel={() => {
          setOpen(false)
        }}
        okText='确认'
        cancelText='取消'
        forceRender
        destroyOnClose={true}
      >
        <Form
          size='large'
          form={formInstance}
          name='basic'
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          autoComplete='off'
          labelAlign='left'
        >
          <Form.Item label='轮播图图片' name='img'>
            <Upload
              action='https://www.mocky.io/v2/5cc8019d300000980a055e76'
              listType='picture-card'
              fileList={fileList}
              onPreview={handlePreview}
              onChange={handleChange}
            >
              {/* {fileList.length >= 8 ? null : uploadButton} */}
            </Upload>
          </Form.Item>
          <Form.Item
            label='跳转链接'
            name='adminname'
            rules={[{ required: true, message: '跳转链接不能为空!' }]}
          >
            <Input
              value={swiperForm.link}
              onChange={e =>
                setSwiperForm({ ...swiperForm, link: e.target.value })
              }
              disabled={mode === 'edit'}
            />
          </Form.Item>

          <Form.Item
            label='alt说明'
            name='alt'
            rules={[{ required: true, message: 'alt不能为空' }]}
          >
            <Input
              value={swiperForm.alt}
              onChange={e =>
                setSwiperForm({ ...swiperForm, alt: e.target.value })
              }
            />
          </Form.Item>
          <Form.Item label='状态' name='status' labelAlign='right'>
            <Switch
              checked={swiperForm.flag}
              onChange={checked => setSwiperForm({ ...swiperForm })}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
